package org.springside.examples.miniweb.service.security;

import java.util.Set;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springside.examples.miniweb.entity.user.Role;
import org.springside.examples.miniweb.entity.user.User;
import org.springside.examples.miniweb.service.user.UserManager;

/**
 * 实现Acegi的UserDetailsService接口,获取用户Detail信息.
 * 
 * @author calvin
 */
public class UserDetailServiceImpl implements UserDetailsService {

	private UserManager userManager;

	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
		User user = userManager.getUserByLoginName(userName);
		if (user == null)
			throw new UsernameNotFoundException(userName + " not found");

		Set<Role> roles = user.getRoles();

		GrantedAuthority[] arrayAuths = new GrantedAuthority[roles.size()];
		int index = 0;
		for (Role role : roles)
			// acegi要求角色名以ROLE_为前缀.
			arrayAuths[index++] = new GrantedAuthorityImpl("ROLE_" + role.getName());

		// 目前在mini-web的User类中没有enabled, accountNonExpired,credentialsNonExpired, accountNonLocked等属性
		// 暂时全部设为true,在需要时才添加这些属性.
		org.acegisecurity.userdetails.User userdetail = new org.acegisecurity.userdetails.User(user.getLoginName(),
				user.getPassword(), true, true, true, true, arrayAuths);

		return userdetail;
	}

	@Required
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
}
